<!-- 路由器质押碎片视图 -->
<template>

  <div class="pag-fegment" >
    <div class="device-pledge-list" v-if="list && list.length > 0">
      <div class="m-table">
          <div class="m-table-head">
            <div class="m-table-row">
              <div class="m-table-cell">序号</div>
              <div class="m-table-cell">节点名称</div>
              <div class="m-table-cell">碎片质押状态</div>
              <div class="m-table-cell">操作</div>
            </div>
          </div>
        <div class="m-table-body">
          <div class="m-list">
            <div class="m-table-row" v-for="(item, index) in list">
              <div class="m-table-cell">{{ nodeNum - index }}</div>
              <div class="m-table-cell">
                {{ item.name }}
                <div v-if="item.miningStatus == 0" class="tag danger">未开启</div>
                <div v-if="item.miningStatus == 1" class="tag success">已开启</div>
              </div>
              <div class="m-table-cell">
                <div class="token-icon" :class="statusObj[item.status]"></div>
              </div>
              <div class="m-table-cell">
                <div class="token-action" :class="typeObj[item.status]"
                     @click="tokenPledgeItemHandle(item)"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 空数据展示页 -->
    <list-empty txt="暂无绑定节点" v-if="list && list.length == 0">
      <div>请绑定节点后再质押</div>
    </list-empty>
    <div class="pledge-actions" ref="pledgeActions" v-show="context.tab == 0 && list && list.length">
      <div @click="tokenPledgeAllHandle('pledge')">批量质押碎片</div>
      <div @click="tokenPledgeAllHandle('revoke')">批量撤销碎片</div>
    </div>
    <!-- 选择质押令牌种类 -->
    <alert ref="tokenPopup" title="选择质押碎片种类" @mask-click="tokenPopupMaskClick">
      <div class="select-token">
        <input type="checkbox" class="f-checkbox" v-model="useBorrow">
        优先质押租用碎片，此次质押不再提示
      </div>
      <template v-slot:footer>
        <div class="use-tokens">
          <div @click="tokenTypeChoose(1)">自有碎片</div>
          <div @click="tokenTypeChoose(0)">租用碎片</div>
        </div>
      </template>
    </alert>
    <!-- 提示框 -->
    <alert ref="tipPopup">
      <div v-if="curTip == 1">今日全网路由器令牌<br>新增放置名额已满无法质押令牌</div>
      <div v-if="curTip == 2">今日全网路由器令牌<br>新增放置名额已满<br>您有<i style="color: #DC0630">{{ todayNode }}</i>个节点无法质押令牌</div>
      <div v-if="curTip == 3">闲置令牌已质押完毕<br>仍有<i style="color: #00A989">{{ todayNode }}</i>个节点没有质押令牌</div>
      <div v-if="curTip == 4" class="tipPopup-p">{{ tip4 }}</div>
    </alert>
  </div>

</template>



<script>
    import { getTokenNodeList, pledgeToken, getPledgeInfo } from 'api'
    import alert from 'cpnts/alert.vue'
    import listEmpty from 'cpnts/list-empty.vue'


    export default {

        components: {
            'alert': alert,
            'listEmpty': listEmpty,
        },
        data() {
            return {
                pledgeInfo: null,
                context: this.$vnode.context,
                isDoActioning: false,
                isTokenActionTransaction: false,
                curTokenData: null,
                useBorrow: false,
                //emptyNode: 18,
                tip4: '',
                curTip: 3,
                showChooseTokenPopup: true,
                scrollY: 0,
                typeNames: {
                    router: '路由器',
                    linux: 'Linux',
                    pc: '客户端',
                },
                typeValues: {
                    router: 3,
                    linux: 2,
                    pc: 1,
                },
                type: 'router',
                options: {
                    pullUpLoad: true
                },
                typeObj: {
                    "1": ["pledge-item-action"],
                    "2": ["revoke-item-action"],
                    "3": ["revoke-item-action"]
                },
                statusObj: {
                    "2": ["token-x"],
                    "3": ["token-z"],
                    "1": ["token-k"],
                },
                list: null
            }
        },
        beforeRouteEnter (to, from, next) {
            next((vm) => {
                // vm.resetData()
                // vm.type = to.query.type
                // vm.getData()
            })
        },
        watch: {
            'context.tab'(val){
                if(val == 0){
                    this.pullUpLoad = this.context.options.pullUpLoad
                    this.context.options.pullUpLoad = true;
                }else {
                    if(this.pullUpLoad === false){
                        this.context.options.pullUpLoad = false;
                    }
                }
                this.context.$refs.scroll.forceUpdate(true)
                //this.context.$refs.scroll.refresh()
                //this.context.$refs.scroll.forceUpdate(true)
            },
            $route(to, from){
                if(to.path.indexOf('/routerPledge') != -1){
                    this.init()
                }
            },
            isDoActioning(val){
                if(val){
                    this.$loading('处理中..')
                }else{
                    this.$loadingHide()
                }
            }
        },
        computed: {
            todayNode(){
                let {nodeNum, nodePledgeNum} = this
                return  nodeNum - nodePledgeNum
            },
            isShowTip3(){
                let {nodeNum, nodePledgeNum, tokenInfo} = this
                let {todayCanPledgeNum} = tokenInfo
                return todayCanPledgeNum > 0 && (nodeNum - nodePledgeNum) > 0
            },
            isShowTip2(){
                let {num, todayCanPledgeNum} = this.tokenInfo
                return todayCanPledgeNum == 0 && num.idleNum > 0
            },
            hasBorrow2(){
                let {miningNum, idleNum} = this.tokenInfo.rentNum
                return idleNum > 0
            },
            hasBorrow(){
                let {incompleteTokenRentNum} = this.tokenInfo[this.type]
                return incompleteTokenRentNum > 0 || this.hasBorrow2
            },
            idleNum2(){
                let {rentNum, num} = this.tokenInfo
                return rentNum.idleNum + num.idleNum
            },
            idleNum(){
                let {incompleteTokenNum, incompleteTokenRentNum} = this.tokenInfo[this.type]
                return this.idleNum2 + incompleteTokenNum + incompleteTokenRentNum
            },
            nodeNum(){
                let {type, tokenInfo} = this
                return tokenInfo[type].nodeNum
            },
            nodePledgeNum(){
                let {type, tokenInfo} = this
                return tokenInfo[type].nodePledgeNum
            },
            tokenInfo(){
                return  this.pledgeInfo || this.$store.state.tokenInfo
            },
            tipContent(){

            }
        },
        mounted(){
            //this.$refs.tokenPopup.show()
            let me = this
            let {context} = me
            context.$el.appendChild(this.$refs.pledgeActions)
            me.init()
            // me.$on('notifyChildren', ()=>{
            //     this.getData()
            //     this.$store.dispatch('getTokenInfo')
            // })
            let onPullingUp = context.onPullingUp
            context.onPullingUp = function (arg) {
                if(context.tab == 1){
                    onPullingUp.call(this, arg)
                } else {
                  me.onPullup()
                }

            }
            //this.getPledgeInfo()
        },
        methods: {
            async getPledgeInfo(){
                let {data} = await getPledgeInfo(3)
                this.pledgeInfo = data
            },
            refresh(){
                this.getData()
                this.getPledgeInfo()
                    //this.$store.dispatch('getTokenInfo')
            },
            init(){
                let vm = this
                vm.resetData()
                vm.type = vm.$route.query.type
                vm.getData()
            },
            resetData(){
                this.hideTipPopup()
                this.hideTokenPopup()
                this.list = null
                this.isTokenActionTransaction = false
                this.isDoActioning = false
                this.useBorrow = false
                this.scrollY= 0
            },
            tokenPopupMaskClick(){
                this.isTokenActionTransaction = false
            },
            tokenPledgeAllHandle(action){
                /*if (action == 'pledge') {
                  this.$warn('功能暂不可用！');
                  return;
                }*/
                this.tokenPledgeHandle({
                    action,
                    //item: null,
                    params: {
                        tokenType: 0,
                        nodeId: 0
                    }
                })
            },
            tokenPledgeItemHandle(item){
                let {status, node_id, tokenType} = item
                let action = status == 1 ? 'pledge' : 'revoke'
                // if(action == 'pledge' && this.tokenInfo.todayCanPledgeNum == 0){
                //     this.curTip = 1
                //     this.showTipPopup()
                //     return
                // }
                /*if (action == 'pledge') {
                  this.$warn('功能暂不可用！');
                  return;
                }*/
                this.tokenPledgeHandle({
                    action,
                    item,
                    params: {
                        tokenType: status == 2 ? 1 : 0,
                        nodeId: node_id
                    }
                })
            },
            tokenPledgeHandle(data){
                let {item, params, action} = data
                // if(!this.idleNum && action == 'pledge'){
                //     return this.$warn('没有可质押的令牌')
                // }
                if(this.isTokenActionTransaction){
                    return
                }
                this.isTokenActionTransaction = true
                //debugger
                if(action == 'pledge'){
                    if(item){
                        //质押单个
                        if(this.hasBorrow){
                            if(this.useBorrow){
                                params.tokenType = 0
                                this.pledgeRevokeTokenAction(data)
                            }else{
                                this.curTokenData = data
                                this.showTokenPopup()
                            }
                        }else {
                            params.tokenType = 1
                            this.pledgeRevokeTokenAction(data)
                        }
                    }else{
                        //质押所有
                        this.pledgeRevokeTokenAction(data)
                    }
                } else {
                    //撤销质押
                    this.pledgeRevokeTokenAction(data)
                }
            },
            async pledgeRevokeTokenAction({item, params, action}){
                let source = action == 'pledge' ? 0 : 1
                this.isDoActioning = true
                try {
                    let payload = Object.assign(
                        {
                            type: this.typeValues[this.type],
                            source
                        }, params)
                    //debugger
                    let {data} = await pledgeToken(payload)
                    if(item){
                        item.status = action == 'pledge' ?  (params.tokenType ? 2 : 3  ) : 1
                    }
                    //this.isTokenActionTransaction = false
                    // this.$store.dispatch('getTokenInfo').then(()=>{
                    //     this.pledgeActionResultTip(action, item)
                    // })
                    this.$suc(action == 'pledge' ? '质押成功！' : '撤销成功!')
                }catch (e) {
                    //this.$warn(e.info || '操作超时')
                    this.curTip = 4
                    this.tip4 = e.info || '操作超时'
                    this.showTipPopup()
                }
                if(!item){
                    this.getData()
                }
                this.isDoActioning = false
                this.isTokenActionTransaction = false
                this.getPledgeInfo()
                //this.$store.dispatch('getTokenInfo')
                this.$emit('notifyParent')
            },
            pledgeActionResultTip(action, item){
                if(action == 'pledge' && !item){
                    this.$once('pledgeActionResult', ()=>{
                        let {isShowTip2, isShowTip3} = this
                        if(isShowTip2){
                            this.curTip = 2
                            this.showTipPopup()
                        }else if(isShowTip3){
                            this.curTip = 3
                            this.showTipPopup()
                        }
                    })
                }
            },
            tokenTypeChoose(tokenType){
                this.hideTokenPopup()
                this.curTokenData.params.tokenType = tokenType
                this.pledgeRevokeTokenAction(this.curTokenData)
            },
            hideTipPopup(){
                this.$refs.tipPopup.hide()
            },
            showTipPopup(){
                this.$refs.tipPopup.show()
            },
            showTokenPopup(){
                this.$refs.tokenPopup.show()
            },
            hideTokenPopup(){
                this.$refs.tokenPopup.hide()
            },
            scrollHandler({ y }) {
                this.scrollY = -y
            },
            getPledgeStatus(status){

            },
            async onPullup(){
                let me = this
                let sc = this.context.$refs.scroll
                if(this.list.length < 20){
                    return this.getData()
                }
                let pagec = Math.floor((this.list.length - 20) / 20) + 1
                let pagey = (this.list.length - 20) % 20

                try {
                    let {data} =  await getTokenNodeList(
                        {
                            type: this.typeValues[this.type],
                            per: 20,
                            page: 1 + pagec
                        }
                    )
                    if(!data){
                        sc.forceUpdate()
                        return
                    }
                    if(pagey){
                        data.splice(0, pagey)
                    }
                    me.list = me.list.concat(data)
                    if(!data.length){
                        sc.forceUpdate()
                    }else{
                        this.$nextTick(()=>{
                            sc.forceUpdate(true)
                        })
                    }
                } catch (e) {
                    this.$warn(e.info)
                    sc.forceUpdate()
                }


            },
            async getData(){
                let sc = this.context.$refs.scroll
                try {
                    let {data} = await getTokenNodeList({
                        type: this.typeValues[this.type],
                        per: 20,
                        page: 1
                    })
                    if(!data){
                        this.list = []
                        sc.forceUpdate()
                        return
                    }
                    this.list = data
                    this.$nextTick(()=>{
                        sc.forceUpdate(true)
                    })
                }catch (e) {
                    this.$warn(e.info)
                    sc.forceUpdate()
                }

            }
        }
    }
</script>





<style lang="scss" scoped>

  .pag-fegment {

  }


  .tips {
    font-size:26px;
    color:rgba(113,118,140,1);
    display: flex;
    align-items: center;
    justify-content: center;
    //height: 80px;
    margin: 28px 0;
    i {
      color: #00A989;
      padding: 0 5px;
      font-style: normal;
    }
    &:before {
      margin-right: 13px;
      flex: 1;
      content: '';
      height:2px;
      background:rgba(205,207,217,1);
      display: inline-block;
    }
    &:after {
      margin-left: 13px;
      flex: 1;
      content: '';
      height:2px;
      background:rgba(205,207,217,1);
      display: inline-block;
    }
  }


  .device-pledge-list {
    margin-top: 28px;
    padding-bottom: 150px;
  }


  .pledge-actions {
    z-index: 80;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #F5F5FB;
    height: 144px;
    div {
      width:330px;
      height:84px;
      background:rgba(23,62,143,1);
      border-radius:10px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size:32px;
      color:rgba(255,255,255,1);
      margin-right: 30px;
      &:last-of-type {
        margin-right: 0;
      }
    }
  }


  .m-table {
    height: 100%;
    color: #202C5B;
  }

  .m-table-head {
    //height: 88px;
    .m-table-row {
      height: 72px;
      .m-table-cell{
        &:nth-of-type(2) {
          padding-left: 66px;
        }
      }
    }
  }

  .m-table-body {
    height: calc(100% - 88px);
  }

  .m-table-row {
    display: flex;
    align-items: center;
    //margin-top: 8px;
    background: #fff;
    height: 96px;
    padding: 0 30px;
    border-top: 2px solid #F5F5F5;
  }

  .m-table-cell{
    display: flex;
    align-items: center;
    &:nth-of-type(1) {
      max-width: 11%;
      width: 11%;
      justify-content: start;
    }
    &:nth-of-type(2) {
      max-width: 38%;
      width: 38%;
      //overflow: hidden;
      //justify-content: start;
      align-items: flex-start;
      flex-wrap: wrap;
      flex-direction: column;
      padding-left: 30px;
    }
    &:nth-of-type(3) {
      max-width: 30%;
      width: 30%;
      justify-content: center;
    }
    &:nth-of-type(4) {
      max-width: 22%;
      width: 22%;
      justify-content: flex-end;
    }
  }


  .token-icon {
    width: 74px;
    height: 68px;
    background: center center / contain no-repeat;
  }

  .token-x {
    //height: 60px;
    background-image: url("~assets/images/token/k-fegment.png");
  }

  .token-z {
    //height: 60px;
    background-image: url("~assets/images/token/z-fegment.png");
  }

  .token-k {
    //height: 16px;
    background-image: url("~assets/images/token/empty-fegment.png");
  }

  .token-action {
    width:150px;
    height:60px;
    border:2px solid;
    border-radius:8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size:26px;
  }

  .pledge-item-action {
    border-color: #00A989;
    color: #00A989;
    &:before {
      content: '质押碎片';
      display: inline;
    }
  }

  .revoke-item-action {
    border-color: #DC0630;
    color: #DC0630;
    &:before {
      content: '撤销碎片';
      display: inline;
    }
  }

  .tipPopup-p {
    padding: 0 30px;
  }



</style>

<style lang="scss" scoped>

  .select-token {
    font-size:26px;
    color:rgba(32,44,91,1);
    display: flex;
    align-items: center;
    justify-content: center;
  }


  .use-tokens {
    display: flex;
    height: 100%;
    div {
      flex: 1;
      border-right: 2px solid #D0D4E4;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .f-checkbox {
    width: 34px;
    height: 34px;
    margin-right: 24px;
    border-radius: 50%;
    -webkit-appearance: none;
    appearance: none;
    background: url("~assets/images/token/uncheck.png") center center/contain no-repeat;
    &:before {
      content: '';
      width: 0;
      height: 0;
      background-image: url("~assets/images/token/check.png");
    }
    &:checked {
      background-image: url("~assets/images/token/check.png");
    }
  }

  .empty-list {
    img {
      display: block;
      height: 274px;
      width: 250px;
      margin: 175px auto 84px auto;
    }
    p {
      font-size:36px;
      font-weight:600;
      color:rgba(113,118,140,1);
      text-align: center;
      margin-bottom: 35px;
    }
    div {
      text-align: center;
      font-size:26px;
      color:rgba(113,118,140,1);
    }
  }


  .tag {
    min-width: 73px;
    width:73px;
    height:30px;
    border-radius:4px;
    font-size:20px;
    //font-weight:500;
    color:rgba(255,255,255,1);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    margin-top: 8px;
    //margin-bottom: 8px;
    &.warning {
      background:rgba(247,163,16,1);
    }
    &.success {
      background:#10D592;
    }
    &.danger {
      background:#EB3257;
    }
    &.info {
      background:#697a9b;
    }
  }



</style>


